/**
 * @Author: 陈瑞鹏
 * @Date:   2022-10-17 10:53:35
 * @Last Modified by:   陈瑞鹏
 * @Last Modified time: 2022-10-28 11:04:54
 */
import abiao_utils from 'abiao_utils';
import express from 'express';
import { loginApi } from '../config/api.config';
import configDefault from '../config/config.default';
import server from '../controllers/server.controller';
import user from '../controllers/user.contorller';
import { Code } from '../enum/code.enum';
import Equip from '../models/equip/equip.model';
import Hero from '../models/hero/hero.model';
import HeroFrag from '../models/hero/heroFrag.model';
import Server from '../models/server/server.model';
import Sign from '../models/sign/sign.model';
import Skill from '../models/skill/skill.model';
import AchTask from '../models/task/achTask.model';
import DailyTask from '../models/task/dailyTask.model';
import RandTask from '../models/task/randTask.model';
import User from '../models/user/user.model';
import JWT from '../utils/jwt';
import Result from '../utils/result';
import Gamedata from '../utils/stats/gamedata';
import utils from '../utils/utils';
const loginRoute = express.Router();

/**
* @api {post} /login/qhLogin 群黑登录
* @apiGroup 登录
* @apiParam {String} username 群黑唯一ID
* @apiParam {String} serverid 群黑服务器ID
* @apiParam {String} isadult 群黑参数
* @apiParam {String} time 群黑参数
* @apiParam {String} flag 群黑参数
* @apiName qhLogin
* @apiVersion 1.0.0
*/
loginRoute.post(loginApi.qhLogin, async (req, res) => {
  let { username, serverid, isadult, time, flag } = req.body;
  const lkey = configDefault.qhApiQuery.lkey;
  let signStr = String(username) + String(serverid) + String(isadult) + String(time) + lkey; //签名字符串
  let sign = utils.md5(signStr);

  if (sign != flag) {
    throw new Result(Code.Fail, '验证错误!');
  }

  return res.json({ code: Code.Succ, message: "验证成功!" });
})

/**
* @api {post} /login/enterGame 进入游戏
* @apiGroup 登录
* @apiDescription 创建角色并初始化角色数据  (在进入服务器时请求)
* @apiParam {String} openId 群黑唯一ID
* @apiParam {String} avatar 头像 (不参与加密)
* @apiParam {String} nickName 昵称 (不参与加密)
* @apiParam {Number} serverId 区服ID
* @apiParam {String} gameUrl 游戏地址 (不参与加密)
* @apiParam {String} chanel 渠道
* @apiParam {String} [ecid] 设备码 (不参与加密)  暂时可选
* @apiParam {String} time 时间戳
* @apiParam {String} sign 签名  md5(openId+serverId+time+key)
* @apiName enterGame
* @apiVersion 1.0.0
*/
loginRoute.post(loginApi.enterGame, async (req, res) => {
  let { openId, avatar, nickName, serverId, gameUrl, ecid, time, sign, evaluate } = req.body;

  if (!openId || !avatar || !nickName || !serverId || !gameUrl || !time || !sign) {
    throw new Result(Code.Fail, '缺少参数', req.body);
  }

  const lkey = configDefault.qhApiQuery.lkey;
  let signStr = String(openId) + String(serverId) + String(time) + lkey;
  let flag = utils.md5(signStr);

  if (flag != sign) {
    throw new Result(Code.Fail, '验证错误');
  }


  let ServerRes: any = await Server.findOne({ serverId });
  if (!ServerRes) {
    throw new Result(Code.Fail, '服务器错误');
  }

  if (!ServerRes.isOpen) {
    throw new Result(Code.Fail, `服务器未开启!\n开启时间${ServerRes.createTime}`);
  }

  let ip: string = utils.getClientIp(req);

  let endRole: any = await User.findOne({}).sort({ roleId: -1 });

  let UserRes: any = await User.findOne({ openId, serverId });

  let roleId: number;

  if (!UserRes) {
    roleId = !endRole ? 1 : Number(endRole.roleId) + 1;
    let info = {
      openId,
      roleId,
      avatar,
      nickName,
      serverId,
      regIp: ip,
      loginIp: ip,
      createTime: abiao_utils.date()
    }
    await User.create(info);
  } else {
    roleId = UserRes.roleId;
    if (!UserRes.status) {
      throw new Result(Code.Fail, '角色被封禁!');
    }
  }

  await server.record__into_server(openId, serverId);
  await Gamedata.login_log_record(roleId, ip);
  await user.login_data_init(roleId);

  let token = JWT.generate({ roleId });
  await User.updateOne({ roleId }, { loginIp: ip, token, updateTime: abiao_utils.date() });

  let userRes = await user.getUserInfo(roleId);

  return res.json({ code: Code.Succ, message: "进入游戏", data: [userRes, token] });
})

/**
* @api {post} /login/roleData 获取角色数据
* @apiGroup 登录
* @apiDescription  游戏角色全部数据
* @apiParam {Number} roleId 角色ID
* @apiName roleData
* @apiVersion 1.0.0
*/
loginRoute.post(loginApi.roleData, async (req, res) => {
  let { roleId } = req.body;
  let userInfo: any = await user.getUserInfo(roleId);
  let EquipRes: any = await Equip.find({ roleId });
  let HeroRes: any = await Hero.find({ roleId });
  let SkillRes: any = await Skill.find({ roleId });
  let TowerRes: any = [];
  let SignRes: any = await Sign.find({ roleId });
  let SignDay: number = utils.dateMinus(userInfo.createTime.split(" ")[0], abiao_utils.date(2)) + 1; //签到第几天
  let AchTaskRes = await AchTask.find({ roleId });
  let DailyTaskRes = await DailyTask.find({ roleId });
  let HeroFragRes: any = await HeroFrag.find({ roleId });
  let RandTaskRes = await RandTask.find({ roleId });

  let retData = {
    userInfo,
    EquipRes,
    HeroRes,
    SkillRes,
    TowerRes,
    SignRes,
    SignDay,
    AchTaskRes,
    DailyTaskRes,
    RandTaskRes,
    HeroFragRes
  }
  return res.json({ code: Code.Succ, message: "获取成功", data: retData });
})

export default loginRoute;